<?php

namespace addons\yungift\model;

use addons\yungift\library\Logic;
use addons\yungift\library\ModelTrait;
use addons\yungift\library\Super;
use think\Model;
use traits\model\SoftDelete;

/**
 * 礼卡 - 卡密
 */
class CardCode extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yungift_card_code';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    // 自定义初始化
    protected static function init()
    {
        FundUser::event('before_insert', function ($item) {
            // 对象默认值 - 必须使用当前类来初始化
            Logic::setDefaultValue($item, [
            ]);

            return true;
        });
    }

    // 礼卡数据
    public function cardData()
    {
        return $this->belongsTo(CardMain::class, 'card_id', 'id');
    }

    // 状态
    // 1=未制卡，2=待使用，3=已使用，4=已兑换，5=已失效
    const STATUS_WAIT_CARD    = 1;
    const STATUS_WAIT_VALID   = 2;
    const STATUS_HAS_VALID    = 3;
    const STATUS_HAS_EXCHANGE = 4;
    const STATUS_HAS_INVALID  = 5;

    public static function getStatusList()
    {
        return [
            self::STATUS_WAIT_CARD    => __('未制卡'),
            self::STATUS_WAIT_VALID   => __('已制卡'),
            self::STATUS_HAS_VALID    => __('登录过'),
            self::STATUS_HAS_EXCHANGE => __('兑换过'),
            self::STATUS_HAS_INVALID  => __('已失效')
        ];
    }

    public function getStatusTextAttr($value, $data)
    {
        $statusList = self::getStatusList();

        return $statusList[$data['status']] ?? $data['status'];
    }

    public function getPasswordMixAttr($value, $data)
    {
        return Super::stringHide($data['password']);
    }
}
